#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use chrono::{NaiveDate,NaiveDateTime};
use crate::domain::CustOrderBean;
use crate::domain::CustOrderQueryRequest;
use crate::domain::my_date_format::DATE_FORMAT;
use crate::domain::my_date_time_format::DATE_TIME_FORMAT;
use crate::serviceimpl::user_service::find_user_by_id as service_find_user_by_id;
use crate::serviceimpl::user_service::list_active_users as service_list_active_users;
use crate::serviceimpl::user_service::count_active_user_records as service_count_active_user_records;
use crate::serviceimpl::user_service::update_user as service_update_user;
use crate::serviceimpl::user_service::find_user_shadow_by_user_name as service_find_user_shadow_by_user_name;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::fs;
use tower_http::{trace::TraceLayer};

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserCustRequest {
	pub id: Option<i64>,
	pub user_name: Option<String>,
	pub email: Option<String>,
	pub address: Option<String>,
	pub phone: Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UserPageCustRequest {
	pub page: i32,
	pub rows: i32,
	//pub status_id : i64,
}

pub fn admin_user_cust_controller() -> Router {
	Router::new()
	.route("/user_list", post(admin_user_list))
	.route("/updateUser", post(update_user))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}

pub async fn admin_user_list(Form(user_page_cust_request):Form<UserPageCustRequest>) ->String {
    //let status_id:i64 = 0;
    let mut pageNumber:i32 = user_page_cust_request.page;
    let mut pageSize:i32 = user_page_cust_request.rows;
    if pageNumber == 0 {
        pageNumber = 1;
    }
    if pageSize == 0 {
        pageSize = 10;
    }
	let list = service_list_active_users().await;
	let totalCount:i32 = service_count_active_user_records().await.unwrap().count_num as i32;
    let totalPage:i32 = (totalCount as f64/pageSize as f64).ceil() as i32;
    let limit:usize = pageSize as usize;
    let start:usize = ((pageNumber -1)*pageSize) as usize;

	match list {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(list) => {
		let mut end:usize = start + limit;
		let listlen = list.len();
            if end > listlen {
                end = listlen;
            }
			let json = serde_json::to_string_pretty(&list[start..end]).unwrap();
			//println!("{}", json);
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("pageNumber".to_string(), Value::from(pageNumber));
			map.insert("pageSize".to_string(), Value::from(pageSize));
			map.insert("totalCount".to_string(), Value::from(totalCount));
			map.insert("totalPage".to_string(), Value::from(totalPage));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}


pub async fn update_user(Json(user_cust_request):Json<UserCustRequest>) ->String {
	let id = user_cust_request.id.unwrap_or_default();
	let user_name = user_cust_request.user_name.unwrap_or_default();
	let email = user_cust_request.email.unwrap_or_default();
	let address = user_cust_request.address.unwrap_or_default();
	let phone = user_cust_request.phone.unwrap_or_default();
	let old_user = service_find_user_by_id(id.clone()).await.unwrap();
	let mut ori_user = service_find_user_shadow_by_user_name(old_user.user_name.clone()).await.unwrap();
	ori_user.user_name = user_name;
	ori_user.email = email;
	ori_user.address = address;
	ori_user.phone = phone;

	let _result = service_update_user(ori_user).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}
